package com.atguigu.day10;

import com.atguigu.bean.WaterSensor;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.tuple.Tuple1;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.table.functions.AggregateFunction;
import org.apache.flink.table.functions.TableFunction;

import java.time.Duration;

import static org.apache.flink.table.api.Expressions.$;
import static org.apache.flink.table.api.Expressions.call;

public class Flink05_UDF_AggFun {
    public static void main(String[] args) {
        //1.获取流的执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        //2.从端口读取数据并转为WaterSensor
        SingleOutputStreamOperator<WaterSensor> dataStream = env.socketTextStream("localhost", 9999)
                .map(new MapFunction<String, WaterSensor>() {
                    @Override
                    public WaterSensor map(String value) throws Exception {
                        String[] split = value.split(",");
                        return new WaterSensor(split[0], Long.parseLong(split[1]), Integer.parseInt(split[2]));
                    }
                })
                .assignTimestampsAndWatermarks(WatermarkStrategy
                        .<WaterSensor>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                        .withTimestampAssigner(new SerializableTimestampAssigner<WaterSensor>() {
                            @Override
                            public long extractTimestamp(WaterSensor element, long recordTimestamp) {
                                return element.getTs() * 1000;
                            }
                        })
                );

        //3.获取表的执行环境
        StreamTableEnvironment tableEnv = StreamTableEnvironment.create(env);

        //4.将流转为表
        Table table = tableEnv.fromDataStream(dataStream, $("id"), $("ts").rowtime(), $("vc"));

        //不注册直接使用
//        table.groupBy($("id"))
//                .select($("id"),call(MyVcAvg.class,$("vc")))
//                .execute()
//                .print();

        //先注册再使用
        tableEnv.createTemporarySystemFunction("vcAvg", MyVcAvg.class);

//        table.groupBy($("id"))
//                .select($("id"),call("vcAvg",$("vc")))
//                .execute()
//                .print();

        tableEnv.executeSql("select id,vcAvg(vc) from "+table+" group by id").print();

    }

    //TODO 自定义一个聚合函数（多进一出） 根据id求vc的平均值
    public static class MyAvgAcc{
        public Integer vcSum;
        public Integer vcCount;
    }

    public static class MyVcAvg extends AggregateFunction<Double,MyAvgAcc>{

        @Override
        public MyAvgAcc createAccumulator() {
            MyAvgAcc myAvgAcc = new MyAvgAcc();
            myAvgAcc.vcSum = 0;
            myAvgAcc.vcCount = 0;
            return myAvgAcc;
        }

        public void accumulate(MyAvgAcc acc,Integer value){
            acc.vcSum += value;
            acc.vcCount += 1;
        }


        @Override
        public Double getValue(MyAvgAcc accumulator) {
            return accumulator.vcSum *1D/ accumulator.vcCount;
        }

    }
}
